package com.yand.frame.controller.login;


import com.yand.frame.common.Result;
import com.yand.frame.entity.ActivityMenu;
import com.yand.frame.entity.ActivityUser;
import com.yand.frame.service.LoginService;
import com.yand.frame.utils.ActivityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


/**
 * 登录请求
 */
@Controller
@RequestMapping("/login")
public class LoginController {



    @Autowired
    private LoginService loginService;


    @Bean(name = "loginService")
    public LoginService getIAccountService(){
        return loginService;
    }

    @Autowired
    private ActivityUtil activityUtil;

    /**
     * 解析登录请求
     *  1，获取用户名以及密码
     */
    @PostMapping("/doLogin")
    public ModelAndView doLogin(@RequestParam String  username, @RequestParam String password, Model model){
        ModelAndView modelAndView = new ModelAndView();
        Result result = activityUtil.doLogin(username,password);
        if(result.getCode() == 0){
            //TODO:这边把用户放到redis中
            modelAndView.setViewName("redirect:/");
        }else{
            model.addAttribute("errorMessage",result.getMessage());
            modelAndView.setViewName("forward:/welcome");
        }
            return modelAndView;
    }

    /**
     *  跳转首页
     *  1，获取登录者的信息，获取登录者的菜单信息，放入对象中。
     * @return
     */
    @RequestMapping("/index")
    public String mainPage( Model model){

        //1,从shiro中获取登录信息
        ActivityUser activityUser = (ActivityUser)SecurityUtils.getSubject().getPrincipal();
        //2,从activityUser中获取角色id
        Integer roleId = activityUser.getRoleId();
        //TODO:这边从redis中获取如果resdis中没有则从数据库中获取菜单信息，目前暂时从数据库中获取，先把流程调通
        //TODO:3,通过角色获取菜单信息
        List<ActivityMenu> menuList = loginService.getMenuListByRoleId(roleId);
        model.addAttribute("user",activityUser);
        model.addAttribute("menuList",menuList);
        return  "activity_index";
    }


    /**
     * 登出即退出程序
     * 注销当前登录用户的信息
     * 回到登录页面
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "login";
    }










}
